package com.ts.api.module.common.controller;

import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.RegexUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.exp.BizException;
import com.ts.api.module.protocol.entity.po.ProtocolPO;
import com.ts.api.module.protocol.service.ProtocolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 *  自有渠道(h5/app)-协议展示相关
 */
@RestController
@RequestMapping("/common/protocol")
public class CommonProtocolController {

    @Autowired
    private ProtocolService protocolService;

    /**
     *  根据自有渠道类型-返回协议列表
     *
     *  @return AjaxResult
     */
    @GetMapping("/list")
    public ResultVO<Object> list() {
        //  根据APP及H5类型区分
        Integer channelType = ChannelContext.get().getType();
        return ResultVO.suc(protocolService.listProtocolByType(channelType));
    }

    /**
     *  根据唯一编号返回对应协议名称
     *
     *  @param  uniqueCode
     *  @return AjaxResult
     */
    @GetMapping("/getName/{uniqueCode}")
    public ResultVO<Object> getProtocolName(@PathVariable String uniqueCode) {
        Assert.isNotEmptyThrows(uniqueCode, new BizException(BizEnum.EMPTY));

        List<ProtocolPO> list = protocolService.listProtocolNameByUniqueCode(Collections.singletonList(uniqueCode));

        if (ValidParam.isEmpty(list)) {
            return ResultVO.suc();
        }
        return ResultVO.suc(IteratorUtils.getFirst(list));
    }

    /**
     *  根据唯一编号返回对应协议内容
     *
     *  @param   uniqueCode
     *  @return AjaxResult
     */
    @GetMapping("/getText/{uniqueCode}")
    public ResultVO<Object> getProtocolText(@PathVariable String uniqueCode) {
        if (ValidParam.isEmpty(uniqueCode) || !RegexUtils.isNumEnglish(uniqueCode)) {
            BizException.fastFail(BizEnum.EMPTY);
        }

        ProtocolPO protocolText = protocolService.getProtocolText(uniqueCode);
        return ResultVO.suc(protocolText);
    }
}
